package com.augurit.gis.common.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

/**
 * 字符串操作的辅助类
 * @author jianfeng.shen
 *
 */
public class StringUtil {
	
	public static String arrayToString(String[] stringArray){
		if(stringArray==null ||stringArray.length==0){
			return null;
		}
		String str = "";
		for(int i=0;i<stringArray.length;i++){
			str+=stringArray[i]+",";
		}
		str = str.substring(0, str.length()-1);
		return str;
	}
	
	public static final String SPACE = "&nbsp;&nbsp;";
	public static String getSpace(int spaceCount){
		String space = "";
		if(spaceCount<0)spaceCount=0;
		for(int i=1;i<=spaceCount;i++){
			space += SPACE;
		}
		return space;
	}
	
	
	public static String toString(Object object){
		Field[] fields = object.getClass().getDeclaredFields();
		String str = "";
		for(int i=0;i<fields.length;i++){
			if(!fields[i].getName().equals("serialVersionUID")){
				str += fields[i].getName()+"=";
				try {
					str +=BeanUtils.getProperty(object, fields[i].getName())+",";
				} catch (Exception e) {
				}
			}
		}
		if(str.length()>0){
			str = str.substring(0,str.length()-1);
		}	
		return str;
	}
	public static boolean isNumeric(String input){
		boolean isNumericFlag = false;
		try{
			Integer.parseInt(input);
			isNumericFlag = true;
		}catch (Exception e) {
		}
		return isNumericFlag;
	}
	
	/*
	 * 判断是否可以转换成数值
	 */
	public static boolean isNumeric2(String input){
		if(input == null || input.equals("")){
			return false;
		}
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(input).matches();  
	}
	public static void printStringArray(String[] arrays){
		for(int i=0;i<arrays.length;i++){
			System.out.println(arrays[i]);
		}
	}
	public static String double2Percent(double value){
		value = value * 100;
		return value + "%";
	}
	public static String object2HTMLString(Object object){
		return object2HTMLString(object, false, true, false);
	}
	public static String findValueInMap(HashMap hashMap,String key){
		if(hashMap.get(key)!=null){
			return (String) hashMap.get(key);
		}
		Iterator iterator = hashMap.keySet().iterator();
		while(iterator.hasNext()){
			String keyInMap = (String) iterator.next();
			if(isLike(key, keyInMap)){
				return (String) hashMap.get(keyInMap);
			}
		}
		return null;
	}
	public static boolean isInclue(String str1,String str2){
		int str1Len = str1.length();
		int str1CharInStr2 = 0;
		for(int i=0;i<str1.length();i++){
			char c = str1.charAt(i);
			if(str2.indexOf(c)!=-1){
				str1CharInStr2 ++;
			}
		}
		if(str1CharInStr2+2>str1Len)
			return true;
		else
			return false;
	}
	/**
	 * 判断两个字符串是否相似,相似的条件是:1:长度最多相差1,2:两者最多有一个字符不一样
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean isLike(String str1,String str2){
		if(str1==null&&str2==null){
			return true;
		}else if(str1!=null&&str2!=null){
			if(str1.length()+1<str2.length()||str2.length()+1<str1.length()){
				return false;
			}else{
				boolean like = isInclue(str1, str2);
				if(like){
					like = isInclue(str2, str1);
				}
				return like;
			}
			
		}else{
			return false;
		}
	}

	public static String object2HTMLString(Object object, boolean isInt){
		return object2HTMLString(object, isInt, true, false);
	}
	public static String object2HTMLString(Object object, boolean isInt, boolean showZero){
		return object2HTMLString(object, isInt, showZero, false);
	}

	public static String double2String(Double double1){
		return double2String(double1, 2);
	}
	/**
	 * 格式化Double输出,最大精确到小数点第10位
	 * @param double1
	 * @param count 输入小于0或大于10将被忽略
	 * @return
	 */
	public static String double2String(Double double1,int count){
		if(double1==null){
			return "";
		}
		String match = "0";
		if(count>0&&count<10){
			match += ".";
			for(int i=0;i<count;i++){
				match += "0";
			}
		}
		DecimalFormat df = new DecimalFormat(match);
		return df.format(double1);
	}
	public static String object2HTMLString(Object object, boolean isInt, boolean showZero, boolean twoFlag){
		String value = "";
		if(object!=null){
			value = object.toString();
			if(object instanceof Double){
				DecimalFormat df=new DecimalFormat("#.00"); 
				Double double1 = (Double) object;
				value = df.format(double1);
				if(isInt){
					if(double1%1==0){
						value = value.substring(0,value.indexOf(".0"));
					}
				}
				if(twoFlag){
//						Double double1 = (Double) object;
//						long l = Math.round(double1*100);
//						double1 = (double)l;
//						double1 = double1/100;
//						value = ""+double1;
				}
				if(double1 == 0){
					if(!showZero){
						value = "";
					}else{
						value = "0";
						if(twoFlag){
							value = "0.00";
						}
					}
				}
			}else if(object instanceof Date){
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
				value = dateFormat.format((Date)object);
			}
		}
		return value;
	}
	
	/**
	 * 判断所输入的字符串是事符合严密的日期格式:
	 * 2006-6-6,1595-12-22 返回true
	 * 2006-6-31,2001-13-22 返回false
	 * @param datestr
	 * @return
	 */
	public static boolean checkDateString(String datestr){
		String patternstr = "\\s*([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2}\\s*)";
		java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(patternstr);
		Matcher matcher = pattern.matcher(datestr);
		boolean isDateType = matcher.find();
		if(isDateType){
			String[] dateArray = datestr.split("-");
			try{
				int year = Integer.parseInt(dateArray[0]);
				int month = Integer.parseInt(dateArray[1]);
				int date = Integer.parseInt(dateArray[2]);
				if(month>12||month==0)
					isDateType = false;
				if(date>31||date==0)
					isDateType = false;
				if(month==2){
					if(year%4==0&&date>29)
						isDateType = false;
					if(year%4!=0&&date>28)
						isDateType = false;
				}else if(month==4||month==6||month==9||month==11){
					if(date>30)isDateType = false;
				}
			}catch (Exception e) {
				isDateType = false;
			}
			
		}
		return isDateType;
	}

	public static long showTimeMsg(long startTime, String method) {
		long endTime = System.currentTimeMillis();
		String msg = "方法(步骤): " + method + " 执行了：" + (endTime - startTime)
				+ " 毫秒";
		System.out.println(msg);
		return endTime;
	}
	
	public static void showTimeMsg(long startTime, long endTime, String method) {
		String msg = "方法(步骤): " + method + " 执行了：" + (endTime - startTime)
				+ " 毫秒";
		System.out.println(msg);
	}
	public static String getTimeMsg(long startTime, long endTime, String method) {
		String msg = "方法(步骤): " + method + " 执行了：" + (endTime - startTime)
				+ " 毫秒";
		return msg;
	}

	public static void showSQLErrorMsg(String sql, String sqlv2) {
		System.out.println("执行SQL=" + sql + " 出现错误,转而执行SQL:" + sqlv2);
	}

	public static String cutQueryString(String queryString) {
		int pos = queryString.lastIndexOf(".jsp?");
		String finalString = queryString;
		if (pos != -1) {
			finalString = queryString.substring(pos + 5);
		}
		return finalString;
	}

	public static void main(String[] args) {
//		System.out.println(double2String(0d, 2));
//		System.out.println(formatDouble2Percent(0.782233d, false));
		Double double1 = 123456789123456.1234568;
//		double1 = 1d;
		System.out.println(formatDouble(double1, "###.00", true));
//		System.out.println(formatDouble2EN(123456789123456.1234568));
	}

	public static void printResultSet(ResultSet resultSet) throws SQLException {
		if (resultSet == null)
			return;
		ResultSetMetaData metaData = resultSet.getMetaData();
		int rowCount = metaData.getColumnCount();
		String line = "";
		 String line2 = "";
		for (int i = 1; i < rowCount; i++) {
			line += metaData.getColumnName(i) + " ";
			 line2 += "columnClassName("+i+")="+metaData.getColumnClassName(i)
			 + "# columnName("+i+")="+metaData.getColumnName(i)
			 + "# columnType("+i+")="+metaData.getColumnType(i)
			 + "# columnTypeName("+i+")="+metaData.getColumnTypeName(i)
			 + "# catalogName("+i+")="+metaData.getCatalogName(i)
			 + "# columnLabel("+i+")="+metaData.getColumnLabel(i)
			 + "# metaData.getSchemaName("+i+")="+metaData.getSchemaName(i)
			 + "# metaData.getTableName("+i+")="+metaData.getTableName(i);

		}
		System.out.println(line);
		 System.out.println(line2);
		line = "";
		// columnClassName(1)=java.lang.String# columnName(1)=ZBID#
		// columnType(1)=12# columnTypeName(1)=VARCHAR2# catalogName(1)=#
		// columnLabel(1)=ZBID
		while (resultSet.next()) {
			for (int j = 1; j <= rowCount; j++) {
				String typeName = metaData.getColumnTypeName(j);
				if (typeName.indexOf("VARCHAR") != -1) {
					line += resultSet.getString(j) + "# ";
				} else if (typeName.equals("NUMBER")) {
					line += resultSet.getInt(j) + "# ";
				} else if (typeName.equals("DATE")) {
					line += resultSet.getDate(j).toString() + "# ";
				} else if (typeName.equals("CLOB")) {
					line += resultSet.getClob(j).toString() + "# ";
				}
			}
			System.out.println(line);
			line = "";
		}
	}


	public static String getDateString(String userId) {
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		int millsecond = calendar.get(Calendar.MILLISECOND);
		String ss = "temp" + userId + "#" + calendar.get(Calendar.YEAR)
				+ (month > 9 ? "" + month : "0" + month)
				+ (day > 9 ? "" + day : "0" + day)
				+ (hour > 9 ? "" + hour : "0" + hour)
				+ (minute > 9 ? "" + minute : "0" + minute)
				+ (second > 9 ? "" + second : "0" + second)
				+ (millsecond > 9 ? "" + millsecond : "0" + millsecond) + "#"
				+ new Random().nextInt(1000) + ".jpg";
		System.out.println(ss);
		return ss;
	}


	public static String getFileName(String name){
		int index = name.lastIndexOf(".");
		String fileName = name.substring(0,index);
		return fileName;
	}
	public static String getFileType(String name){
		int index = name.lastIndexOf(".");
		String typeName = name.substring(index+1);
		return typeName;
	}
	public static String getRandomString() {
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		int millsecond = calendar.get(Calendar.MILLISECOND);
		String ss = calendar.get(Calendar.YEAR)
				+ (month > 9 ? "" + month : "0" + month)
				+ (day > 9 ? "" + day : "0" + day)+"-"
				+ (hour > 9 ? "" + hour : "0" + hour)
				+ (minute > 9 ? "" + minute : "0" + minute)
				+ (second > 9 ? "" + second : "0" + second)+"-"
				+ (millsecond > 9 ? "" + millsecond : "0" + millsecond);
		ss += new Random().nextInt(1000);
		return ss;
	}
	public static String getDateString() {
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		String ss = calendar.get(Calendar.YEAR)
				+ (month > 9 ? "" + month : "0" + month)
				+ (day > 9 ? "" + day : "0" + day);
		return ss;
	}


	public static String addParameter(HttpServletRequest request,
			String queryString, String parameterName) {
		if (queryString.indexOf(parameterName) != -1) {
			return queryString;
		}
		String fieldString = "";
		if (request.getParameter(parameterName) != null) {
			fieldString = "&" + parameterName + "="
					+ request.getParameter(parameterName);
		}
		queryString += fieldString;
		return queryString;

	}


	public static boolean hasInClude(String allModelId, String id) {
		String[] models = allModelId.split("#");
		for (int i = 0; i < models.length; i++) {
			if (models[i].equals(id)) {
				return true;
			}
		}
		return false;
	}
	public static String round(String v, int scale) {
		// 四舍五入函数
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		if(v==null||v.equals("&nbsp;")||v.equals(""))
			return "0.00";
		BigDecimal b = new BigDecimal(v);
		BigDecimal one = new BigDecimal("1");
		String ret = b.divide(one, scale, BigDecimal.ROUND_HALF_UP).toString();
		if (ret == null || ret.equals("null")) {
			ret = "0.00";
		}
		return ret;

	}
	public static String round(String v, int scale,boolean zero) {
		// 四舍五入函数
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		if(v==null||v.equals("&nbsp;")||v.equals("")){
			if(zero){
				return "0.00";
			}else{
				return "";
			}
		}
			
		BigDecimal b = new BigDecimal(v);
		BigDecimal one = new BigDecimal("1");
		String ret = b.divide(one, scale, BigDecimal.ROUND_HALF_UP).toString();
		if (ret == null || ret.equals("null")) {
			ret = "0.00";
		}
		return ret;

	}
	public static void printList(List list) {
		if(list==null)return;
		String line = "list.size()="+list.size()+":\r\n";
		for(int i=0;i<list.size();i++){
			line +=list.get(i)+"# ";
			if((i+1)%10==0&&i!=0)line += "\r\n";
		}
		System.out.println(line);
	}
	
	public static void printMap(Map<String, ?> map){
		Iterator<String> iterator = map.keySet().iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			System.out.println(key+"="+map.get(key));
		}
	}
	public static boolean stringIsInArray(String fieldName, String[] arrays) {
		for(int i=0;i<arrays.length;i++){
			if(arrays[i].equals(fieldName)){
				return true;
			}
		}
		return false;
	}
	public static String formatDouble2Percent(Double double1,boolean showZero){
		return formatDouble(double1, "0.00%", showZero);
	}
	public static String formatDouble2EN(Double double1){
		return formatDouble(double1,"#,##0.00",false);
	}
	public static String formatDouble2EN(Double double1,boolean showZero){
		return formatDouble(double1,"#,##0.00",showZero);
	}
	public static String formatDouble(Double double1,String regex,boolean showZero){
		if(double1==null){
			return "";
		}
		if(double1.doubleValue()==0&&!showZero){
			return "";
		}
		String temp = regex;
		if(temp==null||temp.equals("")){
			temp = "##0.00";
		}
		DecimalFormat df=new DecimalFormat(temp); 
		String value = df.format(double1);
		return value;
	}
	public static String formatDouble(Double double1){
		return formatDouble(double1, "##0.00",true);
	}
	public static String formatDouble(Double double1,String regex){
		return formatDouble(double1, regex,true);
	}
	  public static String getInCondition(String[] fieldName, String[] fieldName2) {
		  String condition = " in(";
		  for(int i=0;i<fieldName.length;i++){
			condition +="'"+fieldName[i]+"',";
		}
		  for(int i=0;i<fieldName2.length;i++){
			  condition += "'"+fieldName2[i]+"',";
		  }
		  condition = condition.substring(0,condition.length()-1);
		  condition += ")";
		return condition;
	}
	  
	public static boolean stringInArray(String str,String[] arrays){
		if(arrays!=null && arrays.length!=0){
			if(str!=null){
				for(int i=0;i<arrays.length;i++){
					if(str.equals(arrays[i])){
						return true;
					}
				}
			}
		}
		return false;
	}
	public static String string2HTML(String string) {
		if(string==null)return "&nbsp";
		return string;
	}
	public static String object2CellValue(Object object){
		if(object!=null){
			if(object instanceof Date){
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
					return  dateFormat.format((Date)object);
			}else {
				String string = object.toString();
//				if(string.indexOf("\n")!=-1||string.indexOf("\r")!=-1){
//					System.err.println(string);
//				}
				string = string.replaceAll("\r\n", " ");
				string = string.replaceAll(",", "，");
				return string;
			}
		}
		return "";
	}

}
